package net.lzzy.practices.web.models;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import net.lzzy.practices.constants.ApiConstant;
import net.lzzy.practices.constants.Messages;
import net.lzzy.practices.entities.User;
import net.lzzy.practices.services.UserService;
import net.lzzy.practices.utils.FileUtil;
import net.lzzy.practices.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @author admin
 */
@Api(tags = "用户认证")
@CrossOrigin
@RestController
@RequestMapping(ApiConstant.ROUTE_AUTH_ROOT)
public class AuthApiController {
    private final UserService service;

    @Autowired
    public AuthApiController(UserService service) {
        this.service = service;
    }

    @ApiOperation("登录")
    @PostMapping(value = ApiConstant.ROUTE_AUTH_LOGIN,produces = ApiConstant.API_PRODUCES)
    public ApiResult login(@RequestBody LoginInfo info){
        String userName = info.getUsername();
        String password = info.getPassword();
        String salt = service.getSalt(userName);

        User user = service.check(userName, StringUtil.md5Encode(password, salt));
        if(user == null){
            return new ApiResult(false, Messages.WRONG_PASSWORD.toString(), null);
        }
        if(user.getType()<0){
            return new ApiResult(false,Messages.NO_PERMISSION.toString(),null);
        }
        VmUser vmUser = VmUser.apiLogin(user);
        return new ApiResult(true,Messages.SUCCESS.toString(), vmUser);

    }

    @ApiOperation("判断用户是否存在")
    @ApiImplicitParam(name = "info",value = "用户登录信息",dataType = "LoginInfo",dataTypeClass = LoginInfo.class,
            paramType = "body",required = true)
    @GetMapping(ApiConstant.ROUTE_AUTH_EXISTS)
    public ApiResult isUserExists(@PathVariable String user){

        boolean exists = service.isUserNameOccupied(user);
        return new ApiResult(true,exists ? "用户已存在" : "", exists);
    }

    @ApiOperation("注册新用户")
    @PostMapping(value = ApiConstant.ROUTE_AUTH_REGISTER,produces = ApiConstant.API_PRODUCES)
    public ApiResult register(@RequestBody RegisterInfo info){
        String nick = info.getNick();
        String user = info.getUser();
        String phone = info.getPhone();
        String email = info.getEmail();
        String avatar = info.getAvater();
        String password = info.getPassword();
        boolean teacher = info.isTeacher();
        String salt = UUID.randomUUID().toString();
        if(StringUtil.isEmpty(nick)){
            nick = user;
        }
        if(StringUtil.isEmpty(user) ||
                StringUtil.isEmpty(avatar) ||
                StringUtil.isEmpty(phone) ||
                StringUtil.isEmpty(email)||
                StringUtil.isEmpty(password)){
            return new ApiResult(false,Messages.MISS_ARGS.toString(), null);
        }
        if(!StringUtil.validMail(email) || !StringUtil.validPhone(phone)){
            return new ApiResult(false,Messages.INVALID_FORMAT.toString(), null);
        }
        if(service.isUserNameOccupied(user)){
            return new ApiResult(false,"用户名已被占用",null);
        }
        User usr = new User();
        usr.setAvatar(avatar);
        usr.setPhone(phone);
        usr.setEmail(email);
        usr.setPassword(StringUtil.md5Encode(password, salt));
        usr.setSalt(salt);
        usr.setType(User.TYPE_STUDENT);
        usr.setNickName(nick);
        usr.setUserName(user);
        usr.setApplyTeacher(teacher);
        VmUser vmUser = VmUser.apiLogin(service.register(usr));
        return new ApiResult(true,Messages.SUCCESS.toString(), vmUser);

    }

    @Value("${user.pic}")
    private String path;


    @ApiOperation("上传文件")
    @PostMapping(ApiConstant.ROUTE_AUTH_UPLOAD)
    public ApiResult upload(@RequestParam("avatar") MultipartFile file){
        JSONObject result = FileUtil.uploadWithRandomName(file, path);
        return new ApiResult(result.getBoolean(FileUtil.UPLOAD_PARAM_STATUS),
                result.getString(FileUtil.UPLOAD_PARAM_MESSAGE),
                result.getString(FileUtil.UPLOAD_PARAM_URL));

    }
}
